<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Android UI 专题,">










<meta name="description" content="LayoutParams 是什么？相信很多人都有疑惑，LayoutParams 是什么？不知道大家想过没有，如果定义一个 ViewGroup，然后在这个 ViewGroup 中放若干 view，这些 view 在 ViewGroup 中的大小关系是保存在哪里的呢？ 12345678910111213141516&amp;lt;LinearLayout    xmlns:android=&quot;http://sc">
<meta name="keywords" content="Android UI 专题">
<meta property="og:type" content="article">
<meta property="og:title" content="对LayoutParams的理解">
<meta property="og:url" content="https://zachaxy.github.io/2017/05/11/对LayoutParams的理解/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="LayoutParams 是什么？相信很多人都有疑惑，LayoutParams 是什么？不知道大家想过没有，如果定义一个 ViewGroup，然后在这个 ViewGroup 中放若干 view，这些 view 在 ViewGroup 中的大小关系是保存在哪里的呢？ 12345678910111213141516&amp;lt;LinearLayout    xmlns:android=&quot;http://sc">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.301Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="对LayoutParams的理解">
<meta name="twitter:description" content="LayoutParams 是什么？相信很多人都有疑惑，LayoutParams 是什么？不知道大家想过没有，如果定义一个 ViewGroup，然后在这个 ViewGroup 中放若干 view，这些 view 在 ViewGroup 中的大小关系是保存在哪里的呢？ 12345678910111213141516&amp;lt;LinearLayout    xmlns:android=&quot;http://sc">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/05/11/对LayoutParams的理解/">





  <title>对LayoutParams的理解 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/11/对LayoutParams的理解/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">对LayoutParams的理解</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-11T09:33:25+08:00">
                2017-05-11
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,471
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <h1 id="LayoutParams-是什么？"><a href="#LayoutParams-是什么？" class="headerlink" title="LayoutParams 是什么？"></a>LayoutParams 是什么？</h1><p>相信很多人都有疑惑，LayoutParams 是什么？不知道大家想过没有，如果定义一个 ViewGroup，然后在这个 ViewGroup 中放若干 view，这些 view 在 ViewGroup 中的大小关系是保存在哪里的呢？</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">LinearLayout</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:android</span>=<span class="string">"http://schemas.android.com/apk/res/android"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:tools</span>=<span class="string">"http://schemas.android.com/tools"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:id</span>=<span class="string">"@+id/activity_main"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_width</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_height</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:orientation</span>=<span class="string">"vertical"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">tools:context</span>=<span class="string">"com.zx.readsourcecode.MainActivity"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">TextView</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:id</span>=<span class="string">"@+id/tv"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:layout_width</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:layout_height</span>=<span class="string">"wrap_content"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:text</span>=<span class="string">"文字"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">LinearLayout</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面是一段最简单不过的布局文件，这里我们最常用的一个属性<code>android:layout_width</code>和<code>android:layout_height</code>相信大家再熟悉不过，其实这两个属性对应两个变量 width 和 height，那么这两个变量是哪个类的成员变量呢？答案就是 LayoutParams。虽然之前不知道 LayoutParams 这和类的存在，但是却一直偷偷的使用它。</p>
<h1 id="LayoutParams-的作用"><a href="#LayoutParams-的作用" class="headerlink" title="LayoutParams 的作用"></a>LayoutParams 的作用</h1><p> <strong>LayoutParams 是 View 用来告诉它的父控件如何放置自己的。</strong>基类 LayoutParams（也就是 ViewGroup.LayoutParams）仅仅描述了这个 View 想要的宽度和高度。在 View 的测量过程中，LayoutParams 起到了决定性的作用！</p>
<p>注意：<code>android:layout_width</code>和<code>android:layout_height</code>表面看起来是 TextView 的宽度和高度，相信这是很多人误解的地方，但如果是描述自己的宽高，那么属性名直接定义为<code>android:width</code>和<code>android:height</code>不就行了，为什么前面要加<code>layout_</code>的前缀？这是因为 TextView 既然放在 LinearLayout 中，那么它的宽度和高度并不是由自己决定的，而是由其父容器（这里对应 LinearLayout）来决定的。通过该属性可选的值 <code>match_parent</code>可以看出，这并不是一个具体的值，而是描述为和父容器一样宽，所以宽度是看父容器有多宽，才给子 view 设置多宽的。</p>
<p>而描述 View 直接用它们自己的属性就好了，如<code>textColor</code>和<code>text</code>等等，为什么还需要引入 LayoutParams 呢？因为<code>textColor</code>和<code>text</code>等这样的属性都是只与 TextView 自身有关的，无论这个 TextView 处于什么环境，这些属性都是不变的。而<code>layout_width</code>与<code>layout_marginLeft</code>这样的属性是与它的父控件息息相关的，是父控件通过 LayoutParams 提供这些”layout_”属性给孩子们用的；是父控件根据孩子们的要求（LayoutParams）来决定怎么测量。</p>
<p>所以在 xml 布局中，凡是以<code>layout_</code>开头的属性，均不是 view 自身的，而是它所在的父控件的 LayoutParams 类中的属性，这里的父控件一定是 ViewGroup 的一个子类。</p>
<h1 id="ViewGroup-LayoutParams"><a href="#ViewGroup-LayoutParams" class="headerlink" title="ViewGroup.LayoutParams"></a>ViewGroup.LayoutParams</h1><p>LayoutParams 是 ViewGroup 中的一个静态类，而每个 ViewGroup 的子类（eg：LinearLayout，FrameLayout，RelativeLayout 等）中依然有一个各自的 LayoutParams 的子类，其在 ViewGroup 的 LayoutParams 静态类的基础之上，添加了和具体布局相关的属性，比如 LinearLayout 中特有的 layout_weight 属性，用来指定特定方向的分配比例，再比如 RelativeLayout 特有的 layout_left，用来指定当前 view 和其它子 view 相对位置的属性等。进入源码中看一下 ViewGroup 中静态内部类 LayoutParams。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public static class LayoutParams &#123;</span><br><span class="line"></span><br><span class="line">    @SuppressWarnings(&#123;&quot;UnusedDeclaration&quot;&#125;)</span><br><span class="line">    @Deprecated</span><br><span class="line">    public static final int FILL_PARENT = -1;</span><br><span class="line"></span><br><span class="line">    public static final int MATCH_PARENT = -1;</span><br><span class="line"></span><br><span class="line">    public static final int WRAP_CONTENT = -2;</span><br><span class="line"></span><br><span class="line">    public int width;</span><br><span class="line"></span><br><span class="line">    public int height;</span><br><span class="line">    </span><br><span class="line">    public LayoutParams(Context c, AttributeSet attrs) &#123;</span><br><span class="line">    TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);</span><br><span class="line">    </span><br><span class="line">    	setBaseAttributes(a,</span><br><span class="line">   			 R.styleable.ViewGroup_Layout_layout_width,</span><br><span class="line">   		 	R.styleable.ViewGroup_Layout_layout_height);</span><br><span class="line">    </span><br><span class="line">    	a.recycle();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public LayoutParams(int width, int height) &#123;</span><br><span class="line">        this.width = width;</span><br><span class="line">        this.height = height;</span><br><span class="line">    &#125;</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到其内部的成员变量只有最基本的 width 和 height，对应了布局文件中的<code>android:layout_width</code>和<code>android:layout_height</code>的值，在解析布局文件时，遇到这两个属性，就给对应的 LayoutParams 的这两个成员变量进行赋值了。</p>
<p>在 ViewGroup 中还自带了一个 LayoutParams 的子类 MarginLayoutParams，供不同的布局使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">MarginLayoutParams</span> <span class="keyword">extends</span> <span class="title">ViewGroup</span>.<span class="title">LayoutParams</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> leftMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> topMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> rightMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> bottomMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> startMargin = DEFAULT_MARGIN_RELATIVE;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> endMargin = DEFAULT_MARGIN_RELATIVE;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其添加了 Margin 相关的属性，相对于布局文件的<code>android:layout_marginLeft=&quot;5dp&quot;</code>等属性。</p>
<p><code>LayoutParams</code>其实是父控件提供给子 view 的，好让子 view 选择如何测量和放置自己。所以在子 view 添加到父控件的那一刻，子 view 就应该有<code>LayoutParams</code>了。我们来看看几中常见的在代码中添加 View 的方式：还是上面的布局，这次我们不用 xml，而是用代码来实现一样的效果。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);</span><br><span class="line">TextView textView = <span class="keyword">new</span> TextView(<span class="keyword">this</span>);</span><br><span class="line">LinearLayout.LayoutParams params = <span class="keyword">new</span> LinearLayout.LayoutParams(</span><br><span class="line">        LinearLayout.LayoutParams.MATCH_PARENT,</span><br><span class="line">        LinearLayout.LayoutParams.WRAP_CONTENT);</span><br><span class="line">linearLayout.addView(textView, params);</span><br></pre></td></tr></table></figure>

<p>View 要是想被添加到 ViewGroup 中，是不可能脱离相应的 ViewGroup.LayoutParams，而独立存在的，不信你将布局文件中的<code>android:layout_width</code>和<code>android:layout_height</code>这两个属性删掉，编译器立即报错。</p>
<p>同时在代码中添加上述操作，虽然可以使用如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);</span><br><span class="line">TextView textView = <span class="keyword">new</span> TextView(<span class="keyword">this</span>);</span><br><span class="line">linearLayout.addView(textView);</span><br></pre></td></tr></table></figure>

<p>但是我们追到 addView 方法内部看一下，可以得出结论，调用 addView（view）的方法，对应的 ViewGroup子类会通过 generateDefaultLayoutParams（）方法自动添加一个默认的 LayoutParams。不同的 ViewGroup（这里指的是 LinearLayout）产生具体 LayoutParams 的方法不同。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View child)</span> </span>&#123;</span><br><span class="line">    addView(child, -<span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View child, <span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (child == <span class="keyword">null</span>) &#123;</span><br><span class="line">    	<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Cannot add a null child view to a ViewGroup"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    LayoutParams params = child.getLayoutParams();</span><br><span class="line">    <span class="keyword">if</span> (params == <span class="keyword">null</span>) &#123;</span><br><span class="line">    	params = generateDefaultLayoutParams();</span><br><span class="line">    <span class="keyword">if</span> (params == <span class="keyword">null</span>) &#123;</span><br><span class="line">    	<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"generateDefaultLayoutParams() cannot return null"</span>);</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    addView(child, index, params);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不同的 ViewGroup（布局）产生具体 LayoutParams 的方法不同。看一下 LinearLayout 中的 generateDefaultLayoutParams（）是如何添加的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> LayoutParams <span class="title">generateDefaultLayoutParams</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>很简单的添加了一个宽高均为 wrap_content 的属性。</p>
<p><strong>注：generateDefaultLayoutParams 方法中返回的 LayoutParams 类，是具体的 ViewGroup 子类（这里代表 LinearLayout）中的静态类 LayoutParams，而不是 ViewGroup 中的。</strong></p>
<p>在深入到 addView 中，看一下 view 和 LayoutParams 是如何关联的，这里删除了部分代码，只看主线；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addViewInner</span><span class="params">(View child, <span class="keyword">int</span> index, LayoutParams params,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="keyword">boolean</span> preventRequestLayout)</span> </span>&#123;  </span><br><span class="line"></span><br><span class="line">	<span class="comment">//(1)</span></span><br><span class="line">    <span class="keyword">if</span> (child.getParent() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"The specified child already has a parent. "</span> +</span><br><span class="line">                <span class="string">"You must call removeView() on the child's parent first."</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//(2)</span></span><br><span class="line">    <span class="keyword">if</span> (!checkLayoutParams(params)) &#123;</span><br><span class="line">        params = generateLayoutParams(params);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  	<span class="comment">//(3)preventRequestLayout 参数的默认值是 false；</span></span><br><span class="line">    <span class="keyword">if</span> (preventRequestLayout) &#123;</span><br><span class="line">        child.mLayoutParams = params;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        child.setLayoutParams(params);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  	<span class="comment">//(4)默认值为 -1</span></span><br><span class="line">    <span class="keyword">if</span> (index &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        index = mChildrenCount;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//(5)</span></span><br><span class="line">    addInArray(child, index);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//(6) tell our children，默认值为 false；</span></span><br><span class="line">    <span class="keyword">if</span> (preventRequestLayout) &#123;</span><br><span class="line">        child.assignParent(<span class="keyword">this</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        child.mParent = <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//(7)</span></span><br><span class="line">    dispatchViewAdded(child);</span><br><span class="line"> </span><br><span class="line">  <span class="comment">//......</span></span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里看一下 addViewInner 方法内部的执行流程</p>
<ol>
<li>检查 view 是否被别的 ViewGroup 添加过，如果被别的添加过，那么抛出异常</li>
<li>再对 layoutParams 进行检测，如果为 null，执行 generateLayoutParams(params)，这也是最后一次为 view 创建 params 了，这里添加的是 ViewGroup.LayoutParams，一般在 LinearLayout、RelativeLayout 等已有的布局中，addview 中会先执行类似的为 view 创建 params 的方法，添加的是各布局特有的 LayoutParams，但是如果是我们自定义的 ViewGroup，也许没有实现配套的 LayoutParams，所以最后用的是 ViewGroup 中自带的 LayoutParams</li>
<li>将 view 的 layoutParams 设置为当前的 layoutParams，在这里执行了关联</li>
<li>除非我们在 addView(view,index)指定了具体值，否则 index 默认值为 -1，如果是 -1 的话，这一步将 index 改为 ViewGroup 中当前 child view 的总和</li>
<li>ViewGroup 中有一个数组，保存着其所有子 view，这里根据 index 值添加到相应的位置，当然这里也涉及到了数组扩容问题，如果你手动指定的 index 过大，超过了当前 ViewGroup 的 mChildrenCount，那么直接报错，index 过大</li>
<li>为 view 分配 parent，这个 parent 就是添加该子 view 的 ViewGroup</li>
<li>执行了 addView 方法，那么原有的 ViewGroup 的结构势必会发生改变，这时候会执行一个回调，通知当前 ViewGroup 添加或者移除了一个 view；当然这个回调默认是 null，我们可以手动添加该回调，使用<code>setOnHierarchyChangeListener(OnHierarchyChangeListener listener)</code></li>
</ol>
<h1 id="自定义-LayoutParams"><a href="#自定义-LayoutParams" class="headerlink" title="自定义 LayoutParams"></a>自定义 LayoutParams</h1><p>前面提到，每个 ViewGroup 的子类（eg：LinearLayout，FrameLayout，RelativeLayout 等）中依然有一个各自的静态内部类 xxxLayout.LayoutParams，其继承了 ViewGroup#LayoutParams，并根据具体的布局，新增了相关属性，比如 LinearLayout 中特有的 layout_weight 属性，用来指定特定方向的分配比例，再比如 RelativeLayout 特有的 layout_left、layout_right 等，用来指定当前 view 和其它子 view 相对位置的属性等。</p>
<p>前面分析 addView 的流程中也介绍到子 view 要想添加到父容器中，父容器必定会给子 view 指定一个 LayoutParams，脱离了 LayoutParams，view 无法单独存在，view 可以通过其 getLayoutParams 方法获取其父容器为子 view 绑定的 LayoutParams。</p>
<p>使用 Android 官方提供的这些 ViewGroup（eg：LinearLayout，FrameLayout，RelativeLayout 等）在 addView 时都会为 view 设置一个 xxxLayout.LayoutParams，而在我们自定义 ViewGroup 控件的时候，如果没有为自定义的 ViewGroup 添加配套的 LayoutParams，那么最终在执行 addViewInner 方法时，会为 view 添加 ViewGroup#LayoutParams，这个 LayoutParams 是一个最基础的，只有 width 和 height 属性，如果我们想实现自定义的 ViewGroup 特殊需求，那么自定义 LayoutParams 是必不可少的。</p>
<p>关于如何自定义 LayoutParams，以及在自定义 LayoutParams 时要注意哪些问题，请参考实战案例<a href>自定义 ViewGroup——百分比布局</a>，这篇文章会根据具体的 ViewGroup 的功能需求，制定对应的 LayoutParams。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>LayoutParams 的作用：是 View 用来告诉它的父控件如何放置自己的，理解这一点很重要，因为这是 view 在 measure 和 layout 过程中很重要的因素。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/05/11/对LayoutParams的理解/" title="对LayoutParams的理解">https://zachaxy.github.io/2017/05/11/对LayoutParams的理解/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/Android-UI-专题/" rel="tag"># Android UI 专题</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/05/10/手写JVM系列-7-读取class文件/" rel="next" title="手写JVM系列(7)-读取class文件">
                <i class="fa fa-chevron-left"></i> 手写JVM系列(7)-读取class文件
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/05/12/LayoutInflater内部原理/" rel="prev" title="LayoutInflater内部原理">
                LayoutInflater内部原理 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#LayoutParams-是什么？"><span class="nav-number">1.</span> <span class="nav-text">LayoutParams 是什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#LayoutParams-的作用"><span class="nav-number">2.</span> <span class="nav-text">LayoutParams 的作用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ViewGroup-LayoutParams"><span class="nav-number">3.</span> <span class="nav-text">ViewGroup.LayoutParams</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#自定义-LayoutParams"><span class="nav-number">4.</span> <span class="nav-text">自定义 LayoutParams</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
